package la.bbs558.websocket;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import la.bbs558.entity.enums.LoginType;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;

import java.util.List;

import static la.bbs558.websocket.WebSocketServer.TOKEN_TO_SESSION;

@Slf4j
public class WebsocketUtils {
    /**
     * 单发给某人
     */
    @SneakyThrows
    public static void sendMessageByUserId(SocketMessage socketMessage) {
        List<String> tokens = StpUtil.getTokenValueListByLoginId(socketMessage.getToUserId(), LoginType.WEB.toString());
        // 兼容之前的
        List<String> tokens1 = StpUtil.getTokenValueListByLoginId(socketMessage.getToUserId(), LoginType.WEB.toString().toLowerCase());
        tokens.addAll(tokens1);
        for (String token : tokens) {
            Session session = TOKEN_TO_SESSION.get(String.valueOf(token));
            if(session != null && session.isOpen()){
                String messageJson = JSON.toJSONString(socketMessage);
                session.getBasicRemote().sendText(messageJson);
                log.info("发送消息成功，token：{}，消息：{}",token,messageJson);
            }
        }
    }

    /**
     * 群发给所有人
     */
    @SneakyThrows
    public static void sendAllMessage(String msgBody) {
        for (Session session : TOKEN_TO_SESSION.values()) {
            session.getBasicRemote().sendText(msgBody);
            log.info("群发发送消息成功，消息：{}",msgBody);
        }
    }

    @SneakyThrows
    public static void closeSession(Long userId) {
        List<String> tokens = StpUtil.getTokenValueListByLoginId(userId,LoginType.WEB.toString());
        // 兼容之前的
        List<String> tokens1 = StpUtil.getTokenValueListByLoginId(userId, LoginType.WEB.toString().toLowerCase());
        tokens.addAll(tokens1);
        for (String token : tokens) {
            Session session = TOKEN_TO_SESSION.get(String.valueOf(token));
            if(session != null && session.isOpen()){
                session.close();
            }
        }
    }
}
